	package com.glureau.aib.client.equipe;

import java.util.List;

import com.glureau.aib.shared.equipe.PionInfo;
import com.glureau.aib.shared.equipe.PionType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class PionTable {
	private FlexTable m_table = new FlexTable();
	private final PionServiceAsync pionService = GWT.create(PionService.class);

	public void init() {

		m_table.setBorderWidth(1);
		pionService.getPionInfos(Cookies.getCookie("sid"), new AsyncCallback<List<PionInfo>>() {
			public void onFailure(Throwable caught) {
				// Show the RPC error message to the user
				m_table.setText(0, 0, "RPC error : Server unavailable");
				m_table.setText(1, 0, caught.getMessage());
			}

			public void onSuccess(List<PionInfo> result) {
				m_table.setText(0, 0, "Type");
				m_table.setText(0, 1, "Name");
				m_table.setText(0, 2, "IA loaded");
				m_table.setText(0, 3, "Parameters");

				int index = 1;
				for (PionInfo pi : result) {
					PionChangeHandler pionHandler = new PionChangeHandler();
					pionHandler.setPionInfo(pi);

					ListBox list = new ListBox(false);
					list.setName("type");
					int typeIndex = 0;
					int i = 0;
					for (PionType t : PionType.values()) {
						list.addItem(t.toString());
						if(t.equals(pi.getType())) {
							typeIndex = i;
						}
						i++;
					}
					list.setSelectedIndex(typeIndex);
					list.addChangeHandler(pionHandler);
					m_table.setWidget(index, 0, list);
					
					TextBox pionName = new TextBox();
					pionName.setName("name");
					pionName.setText(pi.getName());
					pionName.addChangeHandler(pionHandler);
					m_table.setWidget(index, 1, pionName);

					ListBox aiList = new ListBox(false);
					aiList.setName("ai");
					aiList.addChangeHandler(pionHandler);
					m_table.setWidget(index, 2, aiList);

					TextBox params = new TextBox();
					params.setName("params");
					params.setText(pi.getParameters());
					params.addChangeHandler(pionHandler);
					m_table.setWidget(index, 3, params);
					index++;
				}
			}
		});
	}

	public Widget getWidget() {
		return m_table;
	}
}
